/**
 * 
 * @authors Riche
 * @date    2016-07-05 10:39:22
 * @version 1.1.0
 */

/*Vue.transition('fade', {
    enterClass: 'fadeInLeft',
    leaveClass: 'hide'
});*/

/*Vue.use(VueTouch);*/

var vm = new Vue({
    el: "#app",
    data: {
        photos: [], //轮播图
        infos: [], //列表
        hotInfos: [],
        addShow: false,
        classify: [], //分类
        tabs: 0,
        reqOut: false, //判断请求数据是否已完
        newList: {
            isLoading: true,
            pageSize: PAGESIZE,
            pageIndex: 1
        },
        userSide: false, //左侧页面
        user: {},

        inputText: '',
        showModal: false,
        shareObj: {
            dataID: '',
            shareTit: '',
            sharePic: ''
        }
    },
    created: function() {
        var _self = this;

        // 轮播
        var data = {
            size: "5",
            location: 1
        }
        data = Common.jsonEncode(data);
        Common.ajaxCall({ url: "look_getCarouselList", datatype: 'json', type: 'get', data: data }, function(data) {
            if (data.error_code == 0) {
                _self.photos = data.data;
            } else {
                alert(data.msg);
            }
        });


    },
    compiled: function() {
        var _self = this;
        this.loadPhoto();
        $(document).scroll(function() {
            var docHeight = $(document).height(),
                winHeight = $(window).height();
            if ((docHeight > winHeight)&&($(document).scrollTop() >= docHeight - winHeight)) {
                if (!_self.reqOut) {
                    _self.reqOut = true;
                    var str = '<img class="loading-img" src="images/loading.gif"></img>';
                    myLoad.pullLoad('quesCont', str);
                    _self.loadlist(_self.tabs);

                }
            }
        });

        $(document).on('change.inputText', '.fillInput', function() {
            _self.inputText = $(this).val();
        });

        //查看上次是否有Tab记录的先
        var backoperation = $.getCookie('backoperation');
        if (backoperation && typeof(backoperation) === 'string' && backoperation.length > 0) {
            $.setCookie('backoperation', "");
            //查看上次所保存的tab
            var _tabs = $.getCookie('indextabs');
            if (_tabs) {
                _self.tabs = parseInt(_tabs) > 2 ? 0 : parseInt(_tabs);
            }
        }

        _self.slides(_self.tabs);
        //_self.loadlist(_self.tabs);
    },
    ready: function() {
        $(window).scroll(function() {
            var topH = $(window).scrollTop();
            var swiperH = $('.swiper-container').height();
            if (topH > swiperH) {
                $('.indexTab').addClass('top');
                $('.tabBox').css('padding-top', $('.indexTab').outerHeight());
            } else {
                $('.indexTab').removeClass('top');
                $('.tabBox').css('padding-top', '0');
            }
        });
    },
    /*events: { // 创建监听相应响应子组件的事件
      'share-list': function(msg){ // share-list 是用来监听子组件的方法，当接受到子组件的通知的时候，就把子组件更新的数据更新，这里的msg就是子组件的par_msg
        this.shareReg(msg);
      }
    },*/
    methods: {
        /* 函数节流，有加载问题是再处理
        load:function(){
          var _self = this;
          if ($(document).scrollTop() >= $(document).height() - $(window).height()) {
            if(!_self.reqOut){
              var str = '<img class="loading-img" src="images/loading.gif"></img>';
              myLoad.pullLoad('quesCont',str);
              _self.loadlist(_self.tabs);
             
            }
          }
        },
        throttle:function(method,context){
          clearTimeout(method.tId);
          method.tId=setTimeout(function(){
            method.call(context)
          },500);
        },*/
        loadlist: function(tabs) {
            var _self = this;
            var vModal, target;
            switch (tabs) {
                case 0:
                    var url = 'look_getListByTypeID';
                    var defaults = {
                        pageSize: _self.newList.pageSize,
                        pageIndex: _self.newList.pageIndex,
                        sortType: '2'
                    }

                    var data = $.extend(defaults, {});
                    vModal = _self.newList;
                    target = _self.infos;
                    break;
                case 1:
                    var url = 'look_getListByTypeID';
                    var defaults = {
                        pageSize: _self.newList.pageSize,
                        pageIndex: _self.newList.pageIndex,
                        sortType: '3'
                    };
                    var data = $.extend(defaults, {});

                    vModal = _self.newList;
                    target = _self.hotInfos;
                    break;
            }

            if (!vModal || !vModal.isLoading) return;
            data = Common.jsonEncode(data);
            Common.ajaxCall({ url: url, datatype: 'json', type: 'get', data: data }, function(data) {
                if (data.error_code == 0 && data.data.length > 0) {
                    if (vModal.pageIndex == 1) {
                        target.length = 0;
                    }
                    for (var i = 0; i < data.data.length; i++) {
                        target.push(data.data[i]);
                    }
                    _self.reqOut = false;

                    //实际数据与请求的数据量比较
                    if (data.data.length >= vModal.pageSize) {
                        myLoad.pullHide(); //加载后，把效果去掉
                    } else {
                        _self.reqOut = true;
                        myLoad.noDate(); //暂无数据
                        vModal.isLoading = false;
                    }
                } else {
                    _self.reqOut = true;
                    myLoad.noDate(); //暂无数据
                    vModal.isLoading = false;
                }

                vModal.pageIndex++;
            });

        },
        loadPhoto: function() {
            // 轮播比例
            myJS.imgScale('.j_96', '96', '25');
            myJS.ImgFull('.loadImg', 'images/liby.png');
        },
        slides: function(index, e) {
            var _self = this;
            _self.tabs = index;
            
            _self.infos = [];
            _self.hotInfos = [];
            _self.reqOut = false;
            $.setCookie('indextabs', index); //保存最近的Tab
            $.setCookie('meetingtabs', 0); //清理掉其他的
            if (e && typeof(e) != 'undefined')
                $(e.currentTarget).addClass('on').siblings().removeClass('on');
            switch (index) {
                case 0:
                    // 最新
                    _self.newList = {
                        isLoading: true,
                        pageSize: PAGESIZE,
                        pageIndex: 1
                    };
                    _self.loadlist(_self.tabs);
                    break;
                case 1:
                    // 最热
                    _self.newList = {
                        isLoading: true,
                        pageSize: PAGESIZE,
                        pageIndex: 1
                    };
                    _self.loadlist(_self.tabs);

                    break;
                case 2:
                    // 分类
                    Common.ajaxCall({ url: "look_getTypeList", datatype: 'json', type: 'get' }, function(data) {
                        if (data.error_code == 0) {
                            _self.classify = data.data;
                        } else {
                            alert(data.msg);
                        }
                    });
                    break;
            }
            //返回到顶部
            document.documentElement.scrollTop = document.body.scrollTop = 0;
        },
        search: function() {
            window.location.href = "search.html";
        },
        userSideFn: function() {
            if (this.userSide == false) {
                this.userSide = true;
            } else {
                this.userSide = false;
            }
            var _self = this;
            // 顶部个人信息
            Common.ajaxCall({ url: "user_getUserInfo", datatype: 'json', type: 'post' }, function(data) {
                if (data.error_code == 0) {
                    _self.user = data.data;

                } else {
                    alert(data.msg);
                }
            });
        },
        swipeLeft: function(e) {
            var shareColl = $(e.target).parents('li');
            var drift = ($(e.target).parents('li').width()) / 3;
            var touchDrift = ($(e.target).parents('li').width()) / 10;
            //回复原位置
            $(e.target).parents('ul').children().animate({ left: 0 });
            $(e.target).parents('ul').children().find('.shareColl').animate({ width: 0, right: 0 });

            console.log(e.deltaX);
            if (e.deltaX < 0) { //左滑
                if (e.deltaX < -touchDrift) {
                    $(e.target).parents('li').animate({ left: -drift }, 'fast');
                    var height = $(e.target).parents('li').outerHeight();
                    shareColl.find('.shareColl').animate({ width: drift, right: -drift }, 'fast').show().css('line-height', height + 'px');
                }
            } else { //右滑
                if (e.deltaX > touchDrift) {
                    $(e.target).parents('li').animate({ left: 0 }).find('.shareColl').fadeOut('fast');
                }
            }
        },
        share: function(obj, e) {
            $(e.target).parents('li').animate({ left: 0 }).find('.shareColl').fadeOut('fast'); //将左滑的元素复位
            var _self = this;
            _self.showModal = true;
            console.log(obj);
            _self.shareObj = {
                dataID: obj.shareId, //文档id
                shareTit: obj.shareTit, //文档标题
                sharePic: obj.sharePic,    //文档图片
                isdoc : obj.isdoc   //是不是文档
            };

        },
        shareReg: function(userList) {
            var _self = this;
            if (!userList) { //如果没选择分享对象回到原来界面
                _self.showModal = false;
                return;
            }
            
            alert({
                close: false,
                text: '分享',
                description: '<div class="clearfix shareTxt"><span class="j_1 photo"><img class="s_34" src="'+Common.wordIcon(_self.shareObj.sharePic,_self.shareObj.isdoc) +'" onerror=\"javascript:this.src=\'images/icon/type/OTHER.png\';this.onerror=null;\"></span><span class="text">' + _self.shareObj.shareTit + '</span></div>',
                fillInput: true,
                kind: 2,
                okEvent: function() {
                    var data = {
                        dataID: _self.shareObj.dataID,
                        userList: userList,
                        comment: _self.inputText,
                        type: 1
                    };
                    data = Common.jsonEncode(data);
                    Common.ajaxCall({ url: 'look_share', datatype: 'json', type: 'get', data: data }, function(data) {
                        if (data.error_code == 0) {
                            var obj = data.data[0];
                            var code = obj.code;
                            var pic = code == 1 ? "moneyPig.png" : "lebel.png";
                            alert({
                                text: '<img src="images/' + pic + '"/>',
                                description: obj.str,
                                kind: 0
                            });
                        } else {
                            alert(data.msg);
                        }
                    });
                }
            });
        },
        //收藏
        Collection: function(obj, e) {
            var _self = this;
            _self.addShow = false;
            $(e.target).parents('li').animate({ left: 0 }).find('.shareColl').fadeOut(); //将左滑的元素复位
            var data = {
                dataID: obj.dataID,
                type: 1,
                isCollection: 1
            };
            data = Common.jsonEncode(data);
            Common.ajaxCall({ url: 'look_addCollection', datatype: 'json', type: 'get', data: data }, function(data) {
                if (data.error_code == 0) {
                    var obj = data.data[0];
                    var code = obj.code;
                    var pic = code == 1 ? "moneyPig.png" : "lebel.png";
                    alert({
                        text: '<img src="images/' + pic + '"/>',
                        description: obj.str,
                        kind: 0
                    });
                } else {
                    alert(data.msg);
                }
            });
        },
        //进行测试方面的调用
        TestingPage: function(index) {
            var bOK = $.getCookie('TestingCode');
            if (bOK != 'true') {
                bOK = $.getUrlVar("TestingCode");
            }
            if (bOK != 'true') {
                return;
            } else {
                $.setCookie('TestingCode', 'true');
            }
            switch (index) {
                case 1: //我要问
                    {
                        console.log("我要问");
                        location.href = 'asking.html';
                    }
                    break;
                case 2: //知识圈
                    {
                        console.log("知识圈");
                        location.href = 'knowledge.html';
                    }
                    break;
                case 3: //用户中心
                    {
                        console.log("用户中心");
                        this.userSideFn();
                    }
                    break;
            }
        }
    },
    watch: {
        "photos": function() {
            var swiper = new Swiper('.full2', {
                pagination: '.full2 .pagination',
                paginationClickable: true,
                autoplay: 4000,
                loop: true,
                autoplayDisableOnInteraction: false
            });

            this.loadPhoto();
        },
        "showModal": function() {
            var swiper = new Swiper('.full2', {
                pagination: '.full2 .pagination',
                paginationClickable: true,
                autoplay: 4000,
                loop: true,
                autoplayDisableOnInteraction: false
            });

            this.loadPhoto();
        }
    }
});